<?php
/**
 * 公司产品(基础产品)
 * (model)
 */
namespace App\Models\Product;

use App\Models\Basics\Supplier;
use App\Models\Inventory\InventoryCn;
use App\Models\OverSeasBa\DropshippingInventoryFnsku;
use App\Models\OverSeasBa\InventoryBoxFNSku;
use App\Models\OverSeasBa\RemovaleInventoryFNSku;
use App\Models\SalesReport\FBAInventory;
use App\Util\User;
use Encore\Admin\Traits\Resizable;
use Illuminate\Contracts\Support\Arrayable;
use App\Func\UploadFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Database\Eloquent\Model;
class ProductSku extends Model
{
    use Resizable;

    protected $table = 'product_sku';

    protected $guarded = [];

    public static $_isMix = [
        0 => '普通',
        1 => '组合'
    ];

    public static $_mixMode = [
        1 => '人工组合',
        2 => '系统组合'
    ];

    public static $_isSales = [
        0 => '否',
        1 => '是'
    ];

    const PSKUSTATUS_NEW    = 1; //新产品（此产品状态，已弃用）
    const PSKUSTATUS_NORMAL = 2; //正常产品
    const PSKUSTATUS_OUT    = 3; //淘汰产品
    public static $_pSkuStatus = [
        self::PSKUSTATUS_NORMAL => '正常产品',
        self::PSKUSTATUS_OUT    => '淘汰产品'
    ];

    //状态
    const STATUS_YES = 1; //产品启用
    const STATUS_NO  = 2; //产品停用
    public static $_status = [
        self::STATUS_YES => '启用',
        self::STATUS_NO  => '停用',
    ];

    //是否为品牌产品
    const BRAND_YES = 1; //是
    const BRAND_NO  = 2; //否（非品牌产品）
    public static $_brand = [
        self::BRAND_YES => '是',
        self::BRAND_NO  => '否',
    ];

    //默认会基于当前模型名(ProductSku)来决定外键名称：模型名_id
    public function packing(){
        return $this->hasOne(ProductPacking::class,'psku_id');
    }

    public function packing_box(){
        return $this->hasMany(ProductPackingBox::class,'psku_id');
    }

    public function image(){
        return $this->hasOne(ProductImage::class,'psku_id');
    }

    public function classify(){
        return $this->belongsTo(ProductClassify::class,'classify_id');
    }

    public function product_supplier(){
        return $this->hasOne(ProductSupplier::class,'psku_id')->where('status',1);
    }


    public function inventory_cn(){
        return $this->hasMany(InventoryCn::class, 'psku_id', 'id');
    }
    public function inventory_fba(){
        return $this->hasMany(FBAInventory::class, 'psku_id', 'id');
    }
    public function os_box(){
        return $this->hasMany(InventoryBoxFNSku::class, 'psku_id', 'id');
    }
    public function os_removale(){
        return $this->hasMany(RemovaleInventoryFNSku::class, 'psku_id', 'id');
    }
    public function os_dropshipping(){
        return $this->hasMany(DropshippingInventoryFnsku::class, 'psku_id', 'id');
    }

    public static function options($where = [])
    {
        $query = $where ? self::query()->where([$where]) : self::query();
        return $query->where('status', 1)->pluck('psku_code','id');
    }

    //写关联关系的方法时方法名必须是《小写》
    public function suppliers(){
        return $this->belongsToMany(Supplier::class,'product_supplier','psku_id','supplier_id')
            ->using(ProductSupplier::class)
            ->withPivot('moq', 'supplier_price',  'unit_price', 'purchase_cycle', 'status');
    }

    public static function tax($unitPrice,$tax,$num = 1){
        return ($unitPrice / (100 + $tax) * 100) * $num;
    }

    /**
     * 获取产品关联的销售
     * @param $pSkuId
     * @return string
     */
    public static function getSellers($pSkuId){
        $sellerIds = ProductAmazonSku::query()
            ->where('psku_id',$pSkuId)
            ->distinct()
            ->pluck('seller_id');
        return $sellerIds->filter()->map(function ($id){
            return User::getUsernameById($id);
        })->implode('，');
    }

    /**
     * 获取主图src
     * @param        $value
     * @param string $server
     * @return string
     */
    public static function getMainImageSrc($value, $server = ''){
        if(!$value){
            return '';
        }else{
            if (url()->isValidUrl($value)) {
                $src = $value;
            } elseif ($server) {
                $src = $server.$value;
            } else {
                $src = Storage::disk(config('admin.upload.disk'))->url($value);
            }
            return $src;
        }
    }

    public static function getMainImageSrc2($value){
        if(!$value){
            return '';
        }else{
            return public_path('uploads'.DIRECTORY_SEPARATOR.$value);
        }
    }

    /**
     * 获取主图
     * @param        $value
     * @param int    $width
     * @param int    $height
     * @param string $server
     * @return string
     */
    public static function getMainImage($value, $width = 80, $height = 80, $server = ''){
        if(!$value){
            return '';
        }else{
            if (url()->isValidUrl($value)) {
                $src = $value;
            } elseif ($server) {
                $src = $server.$value;
            } else {
                $src = Storage::disk(config('admin.upload.disk'))->url($value);
            }
            return "<a href='$src' data-lightbox='e1'><img src='$src' style='max-width:{$width}px;max-height:{$height}px'></a>";
        }
    }

    /**
     * 读取多图
     * @param        $value
     * @param int    $width
     * @param int    $height
     * @param string $server
     * @return string
     */
    public static function getMultipleImage($value, $width = 200, $height = 200, $server = ''){
        if ($value instanceof Arrayable) {
            $value = $value->toArray();
        }
        return collect((array) $value)->filter()->map(function ($path) use ($server, $width, $height) {
            if (url()->isValidUrl($path)) {
                $src = $path;
            } elseif ($server) {
                $src = $server.$path;
            } else {
                $src = Storage::disk(config('admin.upload.disk'))->url($path);
            }
            return "<a href='$src' data-lightbox='group'><img src='$src' style='max-width:{$width}px;max-height:{$height}px' /></a>";
        })->implode('&nbsp;');
    }

    /**
     * 读取多文件
     * @param        $value
     * @param string $server
     * @return string
     */
    public static function getMultipleFile($value, $server = '')
    {
        if ($value instanceof Arrayable) {
            $value = $value->toArray();
        }
        $uf = UploadFile::getInit();
        $lis = collect((array) $value)->filter()->map(function ($path) use ($server,$uf) {
            $name = basename($path);

            $size = $url = '';

            if (url()->isValidUrl($path)) {
                $url = $path;
            } elseif ($server) {
                $url = $server.$path;
            } else {
                $storage = Storage::disk(config('admin.upload.disk'));
                if ($storage->exists($path)) {
                    $url = $storage->url($path);
                    $size = ($storage->size($path) / 1000).'KB';
                }
            }

            $html = <<<HTML
            <li style="margin-bottom: 0;">
                <span class="mailbox-attachment-icon"><i class="fa {$uf->getFileIcon($name)}"></i></span>
                <div class="mailbox-attachment-info">
                    <div class="mailbox-attachment-name">
                        <i class="fa fa-paperclip"></i> {$name}
                    </div>
                    <span class="mailbox-attachment-size">
                        {$size}&nbsp;
                        <a href="{$url}" class="btn btn-default btn-xs pull-right" target="_blank"><i class="fa fa-cloud-download"></i></a>
                    </span>
                </div>
            </li>
HTML;
            return $html;
        })->implode('&nbsp;');
        return '<ul class="mailbox-attachments clearfix">'.$lis.'</ul>';
    }

    /**
     * 更新普通产品的主产品为其本身
     * @param Model $model
     */
    public static function saveMpSku(Model $model){
        $model->m_psku_id = $model->id;
        $model->m_num = 1;
        $model->save();
    }

    /**
     * 备货审批
     * @param $pSkuId
     * @return array
     */
    public static function getMpSkuById($pSkuId){
        $ps = self::getModelById($pSkuId);
        $item = [];
        if($ps->is_mix == 1){
            $mixRules = explode(',',$ps->mix_rule);
            foreach($mixRules as $i => $mixRule){
                list($pSkuCode,$num) = explode('-',$mixRule);
                $_ps = self::getModelByCode($pSkuCode);
                $item[$i]['psku_id'] = $_ps->id;
                $item[$i]['unit_price'] = $_ps->product_supplier->unit_price ?? 0;
                $item[$i]['num'] = intval($num);
            }
        }else{
            $item[0]['psku_id'] = $pSkuId;
            $item[0]['unit_price'] = $ps->product_supplier->unit_price ?? 0;
            $item[0]['num'] = 1;
        }
        return $item;
    }

    /**
     * 获取默认采购单价
     * @param $model
     * @return float|int
     */
    public static function getPuPrice($model){
        if($model->is_mix == 1){
            $unitPrice = ProductMixSku::getMixSkuPuPrice($model->mix_rule);
        }else{
            $unitPrice = $model->product_supplier->unit_price ?? 0;
        }
        return $unitPrice;
    }

    /**
     * 获取默认采购单价 不含税单价
     * @param $model
     * @return float|int
     */
    public static function getPuPriceNoTax($model){
        if($model->is_mix == 1){
            $unitPrice = ProductMixSku::getMixSkuPuPriceNoTax($model->mix_rule);
        }else{
            $unitPrice = self::tax($model->product_supplier->unit_price ?? 0,$model->product_supplier->supplier->tax ?? 0);
        }
        return round($unitPrice,3);
    }

    public static function getModelById($id){
        return self::query()->find($id);
    }

    public static function getModelByCode($code){
        return self::query()->where('psku_code',$code)->first();
    }

    public static function getValueByCode($code,$field){
        return self::query()->where('psku_code',$code)->value($field);
    }

    public static function getValueById($id,$field){
        return self::query()->where('id',$id)->value($field);
    }

    /**
     * 获取默认生产周期
     * @param $model
     * @return float|int
     */
    public static function getPuCycle($model){
        if($model->is_mix == 1){
            $pCycle = ProductMixSku::getMixSkuPuCycle($model->mix_rule);
        }else{
            $pCycle = $model->product_supplier->purchase_cycle ?? 0;
        }
        return $pCycle;
    }

    /**
     * 获取公司产品列表（公司sku）
     * @param null $classifyId
     * @param null $status
     * @param null $pskuStatus
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getProductSkuList($classifyId = null, $status = null, $pskuStatus = null){

        $query = self::query();
        if($classifyId){
            $query->where('classify_id', $classifyId);
        }
        if ($status){
            $query->where('status', $status);
        }
        if ($pskuStatus){
            $query->where('psku_status', $pskuStatus);
        }

        return $query->get();
    }


    /**
     * 获取产品个数（公司sku）
     * @param null $id
     * @param null $classify_id
     * @param null $status
     * @return int
     */
    public static function getClassifyProductSkuCount($id = null, $classify_id = null, $status = null){
        $query = self::query();
        if ($id) {
            $query->where('id', '<>', $id);
        }
        if ($classify_id) {
            $query->where('classify_id', $classify_id);
        }
        if ($status) {
            $query->where('status', $status);
        }

        return $query->count();
    }

}
